package net.scratch.netty.net.codec;

import net.scratch.netty.util.Packet;
import net.scratch.netty.util.PacketBuffer.PacketSize;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelPipelineCoverage;
import org.jboss.netty.handler.codec.oneone.OneToOneEncoder;

/**
 * 
 * @author 'Mystic Flow
 * @author `Discardedx2
 */

@ChannelPipelineCoverage("all")
public class MessageEncoder extends OneToOneEncoder {


	@Override
	protected Object encode(ChannelHandlerContext ctx, Channel channel, Object msg) throws Exception {
		Packet packet = (Packet) msg;
		if(packet.getOpcode() == -1) {
			 return ChannelBuffers.copiedBuffer(packet.getBuffer(), 0, packet.getLength());
		}
		ChannelBuffer buffer = ChannelBuffers.buffer(1 + packet.getLength() + packet.getSize().size());
		buffer.writeByte((byte) packet.getOpcode());
		if(packet.getSize() == PacketSize.VAR_BYTE) {
			buffer.writeByte((byte) packet.getLength());
		} else if(packet.getSize() == PacketSize.VAR_SHORT) {
			buffer.writeShort((short) packet.getLength());
		}
		buffer.writeBytes(packet.getBuffer());
		return buffer;
	}

}
